// JavaScript Document
importJS('libs/md5.js');
importJS('libs/host.js?t=' + new Date().getTime());
importJS('libs/api.js?t=' + new Date().getTime());
importJS('libs/uploadapi.js');

window.global = { //浏览器版本信息
    browser: (function () {
        var u = window.navigator.userAgent.toLocaleLowerCase(), msie = /(msie) ([\d.]+)/, chrome = /(chrome)\/([\d.]+)/, firefox = /(firefox)\/([\d.]+)/, safari = /(safari)\/([\d.]+)/, opera = /(opera)\/([\d.]+)/, ie11 = /(trident)\/([\d.]+)/, b = u
            .match(msie)
            || u.match(chrome)
            || u.match(firefox)
            || u.match(safari)
            || u.match(opera) || u.match(ie11);
        return {
            name: b[1],
            version: parseInt(b[2])
        };
    })()
}

var Network = {};
var ResponseCode = {
    OK: 200,//成功
    Created: 201,//已创建。成功请求并创建了新的资源
    Unauthorized: 400,//客户端请求的语法错误，服务器无法理解
}

/**
 *
 * @param {String} $url 请求地址
 * @param {String} $method 请求方式 post get
 * @param {Object} $data 参数
 * @param {Function} $onComplete 请求后的回调
 */
Network.connect = function ($url, $method, $data, $onComplete, $async, $encrypt) {
    //请求成功后的数据处理
    var $_onComplete = function ($data) {
        var tempObj = null;
        if (typeof $data == 'string') {
            tempObj = JSON.parse($data);
        } else {
            tempObj = $data;
        }

        //code 500错误信息  400 到登录   200正常  300更新
        if (tempObj.code == ResponseCode.OK || tempObj.code == 500) {
            if ($url == window.api.login) {
                //增加cookie的守护方法，保证用户关闭浏览器后需要重新登录
                Tools.cookie.setItem('uuid_cache_keys',true);
                Tools.setItem("loginInfo", $data.data);
            }
            //JSON全部转为大写的操作
            // if ($data) {
            //     if ($data.data) {
            //         var select = $url.indexOf('select') > -1;
            //         if (select) {
            //             var jsonTemp = Tools.json.upperJSONKey($data.data);
            //             $data.data = jsonTemp;
            //         }
            //     }
            // }

            $onComplete($data);
        }
        //else if (tempObj.code == 300) { //需要更新
        //    Tools.checkVer(tempObj.object);
        //}
        else if (tempObj.code == ResponseCode.Unauthorized) {//需要用户认证身份信息，重新登录
            Tools.alert(tempObj.message, function () { location.href = window.router.logout; });
        }
        else {
            Tools.alert(tempObj.message);
        }
    };
    //如果cookie不存在，那么需要清空loginInfo
    if (!Tools.cookie.getItem('tang4j_cache_uuid')) {
        Tools.removeItem("loginInfo")
    }
    //参数配置
    var body = '',
        conTy = 'application/json;charset=UTF-8',
        loginInfo = Tools.getItem("loginInfo");
    if ($encrypt == undefined) {
        $encrypt = true;
    }
    //除登录外参数加密
    if ($url != window.api.login && $encrypt) {
        var obj = Base64(JSON.stringify($data));
        var randomKey = '';
        if (loginInfo && loginInfo.randomKey != undefined) {
            randomKey = loginInfo.randomKey ? loginInfo.randomKey : '';
        }
        var sign = md5(obj + randomKey).toString();
        $data = {
            object: obj,
            sign: sign
        };

        if (loginInfo == "undefined" || loginInfo == null) {
            Tools.show('请求失败');
        }
    }
    //处理请求参数
    if (!$data)
        $data = '';
    if (!$method) {
        Tools.show('请求失败');
        return;
    }

    if ($data == null || $data == '') {
        $data = {};
    }
    body = JSON.stringify($data);
    
    if ($async == undefined) {
        $async = true;
    }

    //ajax请求
    $.ajax({
        url: $url,
        data: body,
        async: $async,
		    dataType: 'json',
        type: $method,
        timeout: 60000,
        contentType: conTy,
        //async: false, //设为false就是同步请求
        beforeSend: function (xhr) {
            var uuid = Tools.getItem("uuid");
            if (uuid === "undefined" || uuid == null || uuid === '') {
                uuid = Tools.cookie.getItem('tang4j_cache_uuid');
                if (uuid === undefined || uuid === '') {
                    uuid = Tools.uuid();
                }
                else {
                    Tools.cookie.setItem('tang4j_cache_uuid',uuid,15);//自动保留15天的uuid
                }
                
                Tools.setItem("uuid", uuid);
            }

            xhr.setRequestHeader('uuid', uuid);
            xhr.setRequestHeader('version', '1.0.0');
            xhr.setRequestHeader('os', global.browser.name + global.browser.version);
            xhr.setRequestHeader('osType', 'web_tang4j');

            if (loginInfo && $url !== window.api.login) {
                var token = loginInfo.token;
                xhr.setRequestHeader('Authorization', 'Bearer-' + token);
            }
        },
        success: function (data) {
            $_onComplete(data);
        },
        error: function (xhr, type, errorThrown) {
            //异常处理；
            if (type == 'timeout') {
                top.$.messager.show({ title: lan.message.show.title, msg: lan.message.ajaxTimeout, timeout: 5000, showType: 'slide' });
                //top.$.messager.alert({ title: lan.message.alert.title, msg: tempObj.message });
            } else {
                top.$.messager.show({ title: lan.message.show.title, msg: lan.message.ajaxError, timeout: 5000, showType: 'slide' });
            }
        }
    });
};
/*base64编码处理*/
var _keyStr =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
function Base64(input) {
    var output = "",
        chr1,
        chr2,
        chr3,
        enc1,
        enc2,
        enc3,
        enc4,
        i = 0;
    input = _utf8_encode(input);
    while (i < input.length) {
        chr1 = input.charCodeAt(i++);
        chr2 = input.charCodeAt(i++);
        chr3 = input.charCodeAt(i++);
        enc1 = chr1 >> 2;
        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
        enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
        enc4 = chr3 & 63;
        if (isNaN(chr2)) {
            enc3 = enc4 = 64;
        } else if (isNaN(chr3)) {
            enc4 = 64;
        }
        output =
            output +
            _keyStr.charAt(enc1) +
            _keyStr.charAt(enc2) +
            _keyStr.charAt(enc3) +
            _keyStr.charAt(enc4);
    }
    return output;
}
function _utf8_encode(string) {
    string = string.replace(/\r\n/g, "\n");
    var utftext = "";
    for (var n = 0; n < string.length; n++) {
        var c = string.charCodeAt(n);
        if (c < 128) {
            utftext += String.fromCharCode(c);
        } else if (c > 127 && c < 2048) {
            utftext += String.fromCharCode((c >> 6) | 192);
            utftext += String.fromCharCode((c & 63) | 128);
        } else {
            utftext += String.fromCharCode((c >> 12) | 224);
            utftext += String.fromCharCode(((c >> 6) & 63) | 128);
            utftext += String.fromCharCode((c & 63) | 128);
        }
    }
    return utftext;
}

